<template>
  <div class="custom-select">
    <div class="select-box" @click="toggleDropdown">
      <span>{{ selectedLabel }}</span>
      <span class="arrow" :class="{ open: dropdownOpen }"></span>
    </div>
    <ul v-if="dropdownOpen" class="dropdown">
      <li
        v-for="option in options"
        :key="option.value"
        @click="selectOption(option)"
        :class="{ selected: option.value === selectedValue }"
      >
        {{ option.label }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, watch } from "vue";

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: "",
  },
  options: { type: Array, default: () => [] },
});
const emit = defineEmits(["update:modelValue", "change"]);

const selectedValue = ref(props.modelValue);
const dropdownOpen = ref(false);
const selectedLabel = computed(() => {
  const selected = props.options.find(
    (option) => option.value === selectedValue.value
  );
  return selected ? selected.label : "Please select";
});

const toggleDropdown = () => {
  dropdownOpen.value = !dropdownOpen.value;
};

const selectOption = (option) => {
  selectedValue.value = option.value;
  emit("update:modelValue", option.value);
  emit("change", option.value);
  dropdownOpen.value = false;
};

watch(
  () => props.modelValue,
  (newValue) => {
    selectedValue.value = newValue;
  }
);
</script>

<style></style>
